package me.ahoukuse.koala.util;

import io.jsonwebtoken.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.UUID;

public class JwtUtil {

    // 设置 token 过期时间(单位:毫秒)：目前为 1 小时
    private static final long ttl = 60 * 60 * 1000;
    // Signature 签名
    private static final String signature = "Ahoukuse";


    public static String createToken(String userId) {
        JwtBuilder jwtBuilder = Jwts.builder();
        return jwtBuilder
                .setHeaderParam("typ", "JWT")
                .setHeaderParam("alg", "HS256")
                .setId(UUID.randomUUID().toString())
                .setSubject("Access Token")
                .setExpiration(new Date(System.currentTimeMillis() + ttl))
                .setIssuer("Koala Driver")
                .setIssuedAt(new Date())
                .claim("userId", userId)
                .claim("role", "user")
                .signWith(SignatureAlgorithm.HS256, signature)
                .compact();
    }


    public static boolean parseToken(String token) {
        if (token == null) {
            return false;
        }
        JwtParser jwtParser = Jwts.parser();
        try {
            jwtParser.setSigningKey(signature).parseClaimsJws(token);
        } catch (Exception e) {
            return false;
        }
        return true;
    }

    public static Claims parseClaims(String token) {
        if (token == null) {
            return null;
        }
        JwtParser jwtParser = Jwts.parser();
        try {
            return jwtParser.setSigningKey(signature).parseClaimsJws(token).getBody();
        } catch (Exception e) {
            return null;
        }
    }

    public static int getUserIdFromJwt() {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (requestAttributes == null) {
            throw new RuntimeException();
        }
        HttpServletRequest request = requestAttributes.getRequest();
        String authorization = request.getHeader("Authorization");
        String[] auths = authorization.trim().split(" ");
        String token = auths[1].trim();
        Claims claims = parseClaims(token);

        if (claims == null) {
            throw new RuntimeException();
        }

        return Integer.parseInt(claims.get("userId").toString());
    }

}
